﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MkvSplicer.Video
{
    static class Timecodes
    {
        /*
         * Converts a formatted time into a timecode (milliseconds)
         * Accepts: HH:MM:SS.MS, MM:SS.MS, SS.MS, MS
         */
        public static long ParseFormattedTime(string input)
        {
            long result = 0;
            long[] multipliers = { 1L, 1000L, 60000L, 3600000L };
            string[] parts = input.Split(new char[] { ':', '.', ',' },
                                    StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length > 4 )
                throw new FormatException("Invalid timecode format");

            if (parts.Length > 1)
                parts[parts.Length - 1] = parts[parts.Length - 1].PadRight(3, '0');
            for (int i = 0, j = parts.Length - 1; i < parts.Length; i++)
            {
                result += long.Parse(parts[i]) * multipliers[j - i];
            }

            return result;
        }

        public static string FormatTime(long timecode)
        {
            return String.Format("{0:d2}:{1:d2}:{2:d2}.{3:d3}",
                timecode / 3600000L, (timecode % 3600000L) / 60000L,
                (timecode % 60000L) / 1000L, timecode % 1000L);
        }
    }
}
